/* eslint-disable compat/compat */
import React, { useEffect, useState, useCallback } from "react";
import type { GetProp, TableProps } from "antd";
import { Table, Card, message } from "antd";
import type { SorterResult } from "antd/es/table/interface";
import { TruckOrderTrackVO, TruckOrderVo } from "../../types";
import { pageListTruckOrderTracks } from "@/services/order/order_api";
import { useIntl } from "@umijs/max";


type ColumnsType<T extends object = object> = TableProps<T>["columns"];
type TablePaginationConfig = Exclude<
  GetProp<TableProps, "pagination">,
  boolean
>;

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: SorterResult<any>["field"];
  sortOrder?: SorterResult<any>["order"];
  filters?: Parameters<GetProp<TableProps, "onChange">>[1];
}

interface FormProps {
  data?: TruckOrderVo;
}

const TrackListApp: React.FC<FormProps> = ({ data }) => {
  const intl = useIntl();
  const [dataSources, setDataSource] = useState<TruckOrderTrackVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  useEffect(() => {
    queryDate(tableParams);
  }, [data]);

  const queryDate = async (params:any) => {
    if (!data?.orderCode) return;
    // console.log("queryDate", data.orderCode);
    try {
      setLoading(true);
      const pageParams = {
        current: params.pagination?.current,
        pageSize: params.pagination?.pageSize,
        orderCode: data?.orderCode,
      };
      // console.log("queryDate",pageParams);
      const response = await pageListTruckOrderTracks(pageParams);
      if (response.code !== 0) {
        const errorMessage =
          response.msg || intl.formatMessage({ id: "request.error.default" });
        throw new Error(errorMessage);
      }

      setDataSource(
        Array.isArray(response.data.data) ? response.data.data : []
      );
      setTableParams((prev) => ({
        ...prev,
        pagination: {
          ...prev.pagination,
          total: response.data.total || 0,
        },
      }));
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      } else {
        message.error(intl.formatMessage({ id: "request.error.unknown" }));
      }
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<TruckOrderTrackVO> = [
  {
    title: intl.formatMessage({ id: 'pages.track.columns.index' }),
    dataIndex: "index",
    width: 60,
    fixed: "left",
    align: "center",
    render: (_, __, index) => {
      const { current = 1, pageSize = 10 } = tableParams.pagination || {};
      return (current - 1) * pageSize + index + 1;
    },
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.location' }),
    dataIndex: 'location',
    key: 'location',
    width: 120,
    render: (_, record) => (
      <span>
        {[record.city, record.state].filter(Boolean).join(', ')}
      </span>
    ),
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.nextStop' }),
    dataIndex: 'deliveryLocationName',
    key: 'deliveryLocationName',
    width: 180,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.previousStop' }),
    dataIndex: 'pickupLocationName',
    key: 'pickupLocationName',
    width: 180,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.eventType' }),
    dataIndex: 'eventType',
    key: 'eventType',
    width: 150,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.timestamp' }),
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 180,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.statusDesc' }),
    dataIndex: 'status',
    key: 'status',
    width: 150,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.refNumber' }),
    dataIndex: 'shipmentReferenceNumber',
    key: 'shipmentReferenceNumber',
    width: 150,
  },
  {
    title: intl.formatMessage({ id: 'pages.track.columns.proNumber' }),
    dataIndex: 'proNumber',
    key: 'proNumber',
    width: 120,
  },  
  {
    title: intl.formatMessage({ id: 'pages.track.columns.eventTypeDesc' }),
    dataIndex: 'eventTypeDesc',
    key: 'eventTypeDesc',
    width: 150,
  },  
];

  const handleTableChange: TableProps<TruckOrderTrackVO>["onChange"] = async (
    pagination,
    filters,
    sorter
  ) => {
     const newParams = {
    pagination,
    filters,
    sortOrder: Array.isArray(sorter) ? undefined : sorter.order,
    sortField: Array.isArray(sorter) ? undefined : sorter.field,
  };
    setTableParams(newParams);
    await queryDate(newParams);
  };

  return (
    <Card>
      <Table<TruckOrderTrackVO>
        columns={columns}
        rowKey={(record) => record.otId?.toString() || Math.random().toString()}
        dataSource={dataSources}
        pagination={{
          ...tableParams.pagination,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50", "100"],
        }}
        loading={loading}
        onChange={handleTableChange}
        scroll={{ x: 800 }}
      />
    </Card>
  );
};

export default TrackListApp;
